<template>
  <div class="map_wrapper">
    <div id="map" class="map" />
  </div>
</template>

<script>
import mapinit from '@/utils/map-init.js'
import { region } from '@/utils/coordinate.js'
export default {
  name: 'MyMap',
  props: {
    bases: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      zoom: '7',
      T: null,
      map: null,
      polygon: null,
      first: true
    }
  },
  watch: {
    async bases(newValue) {
      if (this.first) {
        await this.initMap()
        this.first = false
      }
      await this.drawBases(newValue)
    }
  },
  methods: {
    initMap() {
      mapinit.init().then(T => {
        const map = new T.Map('map', {
          minZoom: 4
        })
        // map.disableDoubleClickZoom()
        // map.setMapType(TMAP_HYBRID_MAP)// 设置卫星路网复合地图
        let points = []
        for (let i = 0; i < region.length; i++) {
          var lnglats = region[i].split(',')
          points = []
          for (let j = 0; j < lnglats.length; j++) {
            const lnglat = lnglats[j].split(' ')
            points.push(new T.LngLat(lnglat[0], lnglat[1]))
          }
          const polygon = new T.Polygon(points, {
            color: 'rgb(91,134,229)', weight: 2, opacity: 1, fillColor: 'rgb(91,134,229)', fillOpacity: 0
          })
          map.addControl(new T.Control.MapType())
          // polygon.addEventListener('mouseover', function(e) {
          //   const that = e.target
          //   that.setWeight(5)
          //   that.setFillOpacity(0.3)
          // }).addEventListener('mouseout', function(e) {
          //   const that = e.target
          //   that.setWeight(2)
          //   that.setFillOpacity(0.1)
          // })
          this.T = T
          this.map = map
          this.polygon = polygon
        }
      })
    },
    drawBases(bases) {
      const T = this.T
      this.map.clearOverLays()
      this.map.addOverLay(this.polygon)
      this.map.centerAndZoom(new T.LngLat(114.36768, 31.98012), this.zoom)
      bases.map(item => {
        const marker = new T.Marker(new T.LngLat(item.lng, item.lat))
        marker.addEventListener('mouseover', event => {
          event.target.openInfoWindow(new T.InfoWindow(`${item.siteName}`, { closeOnClick: true }))
        })
        marker.addEventListener('click', event => {
          this.$emit('route-to', item.siteId, item.entId)
        })
        this.map.addOverLay(marker)
      })
    }
  }
}
</script>

<style scoped>
.map_wrapper {
  position:absolute;
  top:0;
  width:100%;
  height:100%;
  z-index:1;
}

.map {
  width: 100%;
  height: 100vh;
}

.map >>> .tdt-control-copyright {
  display: none;
}

</style>
